<template>
  <div class="csp">
    <div class="csp-header">
      <div
        class="cspH--tag"
        :class="[{ 'cspH--tag--default': showTag[0] }]"
        @click="tagChange(0)"
      >
        备课详情
      </div>
      <div
        class="cspH--tag"
        :class="[{ 'cspH--tag--default': showTag[2] }]"
        @click="tagChange(2)"
      >
        课程试题
      </div>
      <div
        class="cspH--tag"
        :class="[{ 'cspH--tag--default': showTag[3] }]"
        @click="tagChange(3)"
      >
        课程作业
      </div>
    </div>
    <div class="csp-content">
      <div class="csp-content-tag" v-if="showTag[0]">
        <div class="csp-content-tag-action">
          <div class="csp-content-tag-action-label">
            <div class="csp-content-tag-action-label-show">
              <div
                class="csp-content-tag-action-label-show-nill"
                v-if="
                  !all_courses.activity_pros ||
                  all_courses.activity_pros.length == 0
                "
              >
                {{ all_courses.duration }}分钟
              </div>
              <div class="csp-content-tag-action-label-show-y" v-else>
                <div
                  :key="index"
                  :style="act.style"
                  v-for="(act, index) in all_courses.activity_pros"
                >
                  {{ act.type }}
                </div>
              </div>
            </div>
          </div>
          <div class="csp-content-tag-action-block">
            <a-dropdown>
              <a-menu slot="overlay" @click="handleMenuClick">
                <a-menu-item :key="index" v-for="(item, index) in activities">
                  <a-icon type="user" />{{ item }}
                </a-menu-item>
              </a-menu>
              <a-button
                style="margin-left: 8px; width: max-content"
                size="small"
              >
                <span v-if="!selecteditem">请选择课堂活动 </span>
                <span v-else>{{ selecteditem }}</span>
                <a-icon type="down" />
              </a-button>
            </a-dropdown>
            <a-input
              v-model="input_txt"
              placeholder="耗时 10"
              size="small"
              style="width: 160px"
            >
              <a-icon slot="prefix" type="dashboard" />
              <a-tooltip slot="suffix" title="Extra information">
                分钟
              </a-tooltip>
            </a-input>
            <button
              class="csp-content-tag-action-block-c"
              @click="add_activity"
            >
              +
            </button>
          </div>
        </div>
        <div class="csp-content-tag-page">
          <div
            class="csp-content-tag-page-wh"
            :key="index"
            v-for="(item, index) in all_courses.activities"
          >
            <div class="csp-content-tag-page-wh-header">
              <span>
                {{ item.activity_type }}
              </span>
              <a-button
                v-if="!all_courses.publish"
                class="deleteActivity"
                icon="minus"
                type="link"
                @click="deleteActivity(index)"
              ></a-button>
            </div>
            <div class="csp-content-tag-page-wh-body">
              <!-- 活动内容部 
                :publish="all_courses.publish"
              -->
              <component
                :is="item.activity_en"
                :activityMessage="item"
              ></component>
            </div>
          </div>
          <a-button @click="storeConfirm">发布</a-button>
        </div>
      </div>

      <div class="csp-content-tag" v-if="showTag[2]">
        <div
          class="resourceBlock"
          style="background: #f9f7f6; padding: 20px; margin-top: 20px"
        >
          <div class="two-btn">
            <button class="content-btn" @click="questionVisible = true">
              添加试题
            </button>
            <button class="content-btn" @click="bulkImport_visible = true">
              批量导入
            </button>
            <!-- <button class="content-btn" @click="mutipleDelete">批量删除</button> -->
          </div>
          <add-question
            :visible.sync="questionVisible"
            @refreshQuestion="refreshQuestion"
          ></add-question>
          <question-list ref="questionList"></question-list>
        </div>
      </div>

      <div class="csp-content-tag" v-if="showTag[3]">
        <div
          class="resourceBlock"
          style="background: #f9f7f6; padding: 20px; margin-top: 20px"
        >
          <div :span="4">
            <button class="content-btn" @click="homeworkVisible = true">
              布置作业
            </button>
          </div>
          <add-homework :visible.sync="homeworkVisible"></add-homework>
          <homework-list></homework-list>
        </div>
      </div>
    </div>
    <div>
      <batch-add-question
        :visible.sync="bulkImport_visible"
        @refreshQuestion="refreshQuestion"
      ></batch-add-question>
    </div>
  </div>
</template>

<script>
// import PreHomework from "./preselect/PreHomework.vue";PreRandomSign
import Teach from "./preselect/PreTeaching.vue";
import Ask from "./preselect/PreQuestion.vue";
import Race from "./preselect/PreCompete.vue";
import Vote from "./preselect/PreVote.vue";
import Sign from "./preselect/PreSign.vue";
import RandomSign from "./preselect/PreRandomSign.vue";
import Dispatch from "./preselect/PreDocument.vue";
import Test from "./preselect/PreTest.vue";
// import PreResource from "./preselect/PreResource";
import AddQuestion from "@/components/teacher/coursedetail/question/AddQuestion";
import AddHomework from "@/components/teacher/coursedetail/homework/AddHomework";
import QuestionList from "./QuestionList";
import HomeworkList from "./HomeworkList";
import axios from "@/utils/axios";
import { mapState, mapGetters } from "vuex";
import fileUploader from "@/utils/S3FileUploader";
import BatchAddQuestion from "./BatchAddQuestion.vue";

export default {
  props: {
    courseHours: Array,
  },
  components: {
    Teach,
    Ask,
    Race,
    Vote,
    Sign,
    Dispatch,
    // PreDocument,
    Test,
    QuestionList,
    HomeworkList,
    AddQuestion,
    RandomSign,
    AddHomework,
    BatchAddQuestion,
  },
  data() {
    return {
      //
      selecteditem: "",
      // 讲课标记
      bulkImport_visible: false,
      upload_url: "",
      radioStyle: {
        display: "block",
        height: "30px",
        lineHeight: "30px",
      },
      ppt: {},
      labelCol: { span: 3 },
      wrapperCol: { span: 14 },
      form: {
        desc1: "",
        time: 50,
      },
      show: false,
      showTag: [true, false, false],
      time: 10,
      oldtime: 0,
      sumtime: 0,
      current: 0,
      steps: [],
      //------------------
      activities: [
        "讲课",
        "签到",
        "投票",
        "提问",
        "抢答",
        "点名",
        "测试",
        "文件下发",
      ],
      input_txt: "",
      all_courses: {
        activities: [],
        activity_pros: [],
      },
      activities_pro: [],
      proStyle: {},
      //---------------
      event: {
        PreVote: "投票",
        PreSign: "签到",
        PreCompete: "抢答",
        PreQuestion: "提问",
        PreTeaching: "讲课",
        PreTest: "随堂测试",
        PreDocument: "文件下发",
        PreRandomSign: "随机点名",
      },
      eventname: {
        PreVote: "Vote",
        PreSign: "Sign",
        PreCompete: "Race",
        PreQuestion: "Ask",
        PreTeaching: "Teach",
        PreTest: "Test",
        PreDocument: "Dispatch",
        PreRandomSign: "randomSign",
      },
      slidervalue: 5,
      modalvisible: false,
      changevisible: false,
      pptvisible: false,
      selectevent: "",
      componentId: "",
      uploadVisible: false,
      questionVisible: false,
      homeworkVisible: false,
    };
  },
  computed: {
    coursePPT() {
      if (this.curCourseHour.PPT) return this.curCourseHour.PPT;
      else return {};
    },
    isempty() {
      if (this.current == -1) {
        return true;
      } else {
        return false;
      }
    },
    ...mapGetters({
      curCourseHour: "teacher/curCourseHour",
      pptsource: "teacher/getPPTSource",
    }),
    ...mapState({
      uid: (state) => state.public.uid,
    }),
    lesson_id() {
      return this.$route.query.lessonId;
    },
    // publish() {
    //   return !this.ppt.id;
    // },
  },
  methods: {
    deleteActivity(index) {
      this.all_courses.activities.splice(index, 1);
    },
    // mutipleDelete() {
    //   console.log("coem-------");
    // },
    refreshQuestion() {
      // 刷新试题
      this.$refs.questionList.getQuestionList();
    },
    // 警告。发布之后不允许修改
    storeConfirm() {
      var that = this;
      this.$confirm({
        title: "发布后不允许更改，确认发布吗?",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          that.storePrecourse();
        },
      });
    },
    // 存储事件
    async storePrecourse() {
      // 检查讲课是否有PPT
      let pptStatus;
      if (!this.all_courses.activities.length) {
        this.$message.error("当前没有活动，不可发布！");
        return;
      }
      await this.all_courses.activities.forEach((activity) => {
        if (activity.tag == "Teach") {
          if (!activity.PPT) {
            pptStatus = false;
          } else {
            pptStatus = true;
            this.all_courses.PPT = activity.PPT;
          }
        }else{
          pptStatus = true;
        }
      });
      if (!pptStatus) {
        this.$message.error("讲课必须要有PPT！");
        return;
      }
      console.log(
        "🚀 ~ file: PreContext.vue ~ line 327 ~ storePrecourse ~ this.all_courses",
        this.all_courses
      );
      await this.$emit("getCourseHour");
      //  [this.$store.state.teacher.curCourseHour]
      // 检查活动信息
      if (!this.judgeNodesBlank(this.all_courses.activities)) {
        this.$info({
          title: "请将活动信息填写完整",
        });
        return;
      }
      // 已发布数据不支持修改
      if (this.all_courses.publish) {
        this.$message.error("已发布数据不支持修改！");
        return;
      }
      // 通知proCollapse获取课时信息\
      // 保存至数据库里
      const url = "pc/v1/prepares/updateOnePrepareLesson";
      let requestData = {
        name: this.courseHours[this.$store.state.teacher.curCourseHour].name,
        lesson_id: this.lesson_id,
        teacher_id: this.uid,
        duration: this.all_courses.duration,
        nodes: this.all_courses.activities.map((activity) => {
          return {
            people_num: activity.people_num,
            tag: activity.tag,
            time: activity.time,
            node_contents: activity.node_contents,
          };
        }),
        PPT: this.all_courses.PPT,
        description: this.all_courses.description,
      };
      const { data } = await axios.post(url, requestData);
      if (data.status) {
        this.$message.info("保存成功!");
        this.$emit("refreshCourseHours");
      } else {
        this.$message.error("保存失败!");
      }
    },
    ////-------the upper section is added by qichao-----------------------------
    handleMenuClick(e) {
      this.selecteditem = this.activities[e.key];
    },
    // 添加活动
    add_activity() {
      // 如果选项为空或时间为空则返回 TODO
      if (!this.input_txt || !this.selecteditem) {
        this.$message.error("请将信息填写完整！");
        return;
      }
      console.log(
        "🚀 ~ file: PreContext.vue ~ line 383 ~ this.all_courses.activities.forEach ~ this.all_courses.activities",
        this.all_courses
      );
      // 判断当前时间是否溢出
      let sumTime = Number(this.input_txt);
      this.all_courses.activities.forEach((activity) => {
        sumTime += activity.activity_duration;
      });
      if (sumTime > this.all_courses.duration) {
        this.$message.error("添加时间超过课堂总课时！");
        return;
      }
      // 判断活动是否已发布

      // 将活动对象加入时间轴
      let temp_act_time = this.input_txt;
      let wRadio = (parseInt(temp_act_time) / this.all_courses.duration) * 100;
      let temp_act_type = this.selecteditem;
      let temp_color = "";
      switch (temp_act_type) {
        case "签到":
          temp_color = "#9FE6B8";
          break;
        case "测试":
          temp_color = "#ffbf00";
          break;
        case "点名":
          temp_color = "#ff9f7f";
          break;
        case "文件下发":
          temp_color = "#fb7293";
          break;
        case "投票":
          temp_color = "#8378EA";
          break;
        case "提问":
          temp_color = "#96BFFF";
          break;
        case "抢答":
          temp_color = "#e7bcf3";
          break;
        case "讲课":
          temp_color = "#00a2ae";
          break;
        default:
          break;
      }
      let temp_style = {
        width: wRadio + "%",
        "background-color": temp_color,
        color: "#ffffff",
        textAlign: "center",
        border: "0",
      };
      // temp_act_time=this.se
      let act = {
        time: temp_act_time,
        type: temp_act_type,
        style: temp_style,
      };
      this.all_courses.activity_pros.push(act);
      // 添加活动对象
      console.log(
        "🚀 ~ file: PreContext.vue ~ line 377 ~ add_activity ~ this.all_courses",
        this.all_courses
      );
      switch (temp_act_type) {
        case "签到":
          temp_act_type = "Sign";
          break;
        case "测试":
          temp_act_type = "Test";
          break;
        case "点名":
          temp_act_type = "randomSign";
          break;
        case "文件下发":
          temp_act_type = "Dispatch";
          break;
        case "投票":
          temp_act_type = "Vote";
          break;
        case "提问":
          temp_act_type = "Ask";
          break;
        case "抢答":
          temp_act_type = "Race";
          break;
        case "讲课":
          temp_act_type = "Teach";
          break;
        default:
          break;
      }
      const node = {
        activity_duration: Number(temp_act_time),
        activity_en: temp_act_type,
        activity_type: this.selecteditem,
        people_num: 3,
        tag: temp_act_type,
        time: temp_act_time + "分钟",
        node_contents: [
          {
            options: ["", "", "", ""],
            question_type: 2,
            right_answer: "",
            title: "",
          },
        ],
      };
      this.all_courses.activities.push(node);
    },
    deletesteps() {
      if (this.steps.length == 0) {
        this.$message.error("当前没有事件，请先添加事件");
        return;
      }
      const that = this;
      this.$confirm({
        title: "确定删除此事件吗?",
        okText: "确定",
        okType: "danger",
        cancelText: "取消",
        onOk() {
          try {
            let time = that.steps[that.current].description.split("分钟")[0];
            that.sumtime -= time;
            console.log("that.steps[that.current]");
            console.log(that.steps[that.current]);
            if (that.steps[that.current].title === "讲课") {
              // 删除ppt
              that.$store.commit("teacher/updatePPT", {});
            }
            that.steps.splice(that.current, 1);
            that.$store.commit("teacher/deleteNode", that.current);

            that.current = that.steps.length - 1;
            that.addChange(that.current);
          } catch (err) {
            console.log(err);
          }
        },
        onCancel() {
          // console.log("Cancel");
        },
      });
    },
    tagChange(key) {
      switch (key) {
        case 0:
          (this.showTag = [true, false, false]), false;
          break;
        case 1:
          (this.showTag = [false, true, false]), false;
          break;
        case 2:
          this.showTag = [false, false, true, false];
          break;
        case 3:
          this.showTag = [false, false, false, true];
          break;
        default:
          break;
      }
    },
    // 判断活动信息是否为空
    judgeNodesBlank(nodes) {
      let judgeStatus = true;
      nodes.forEach((element1) => {
        if (
          element1.tag !== "Teach" &&
          element1.tag !== "Sign" &&
          element1.tag !== "randomSign"
        ) {
          element1.node_contents.forEach((element2) => {
            element2.options.forEach((item) => {
              if (item == "") {
                judgeStatus = false;
                return;
              }
            });
          });
        }
      });
      return judgeStatus;
    },
  },
  watch: {
    curCourseHour(value) {
      console.log(
        "🚀 ~ file: PreContext.vue ~ line 595 ~ curCourseHour ~ value",
        value
      );
      try {
        // 设置用于显示的活动
        let tagToShow = {
          Teach: "讲课",
          Sign: "签到",
          Ask: "提问",
          Vote: "投票",
          Race: "抢答",
          randomSign: "点名",
          Dispatch: "文件下发",
          Test: "随堂测试",
        };
        let tagToColor = {
          Teach: "#00a2ae",
          Sign: "#9FE688",
          Ask: "#96BFFF",
          Vote: "#8378EA",
          Race: "#e7BCF3",
          randomSign: "#FF9F7F",
          Dispatch: "#FB7293",
          Test: "#FFBF00",
        };
        if (!value.PPT) {
          value.PPT = { name: "", rsId: "", url: "" };
        }
        this.all_courses = {
          PPT: value.PPT,
          activity_pros: value.nodes.map((node) => {
            return {
              type: tagToShow[node.tag],
              time: node.time.split("分")[0],
              style: {
                "background-color": tagToColor[node.tag],
                border: "0",
                color: "#ffffff",
                textAlign: "center",
                width: `${
                  (parseInt(node.time.split("分")[0]) / value.duration) * 100
                }%`,
                "white-space": "nowrap",
                overflow: "hidden",
                "text-overflow": "ellipsis",
              },
            };
          }),
          description: value.description,
          duration: value.duration,
          courseHourName: value.name,
          publish: value.publish,
          activities: value.nodes.map((node) => {
            return {
              activity_type: tagToShow[node.tag],
              activity_en: node.tag,
              activity_duration: Number(node.time.split("分")[0]),
              ...node,
            };
          }),
        };
        console.log(
          "🚀 ~ file: PreContext.vue ~ line 727 ~ curCourseHour ~  this.all_courses ",
          this.all_courses
        );
      } catch (err) {
        console.log(err);
      }
    },
  },
  mounted() {
    // 获取资源
    this.$store.dispatch("teacher/getSources", {
      lesson_id: this.lesson_id,
      teacher_id: this.uid,
    });
  },
};
</script>

<style lang="scss">
.steptype {
  padding: 5px;
  width: 100%;
  overflow-x: auto;
}

.event-btn .ant-btn {
  margin: 0 5px;
}

.box {
  background: #f9f7f6;
  height: 100%;
  margin-top: 10px;
  margin-bottom: 10px;
}

.contextstyle {
  height: 65%;
  padding: 20px;
}

.try {
  width: 100%;
  height: 100%;
  padding: 30px;
}

.precompeteclass {
  background: #fff;
  height: 100%;
  width: 100%;
}
.header-btn .ant-btn {
  margin: 0 5px;
}

.cspH--tag {
  width: 90px;
  padding: 10px;
  font-size: 1.4rem;
  color: #6d757a;
  /* border-bottom: 2px solid #ccc; */
  cursor: pointer;
}
.cspH--tag--default {
  color: #222222;
  border-bottom: 3px solid #ccc;
}
.cspH--tag:hover {
  width: 90px;
  padding: 10px;
  /* border-bottom: 2px solid #ccc; */
}
.deleteActivity {
  float: right;
  color: black;
}
.deleteActivity:hover {
  color: black;
}
</style>
